(:
  A procedure to select the contents of the 2nd worksheet in excel
:)
declare boundary-space strip;
import module namespace
    jj = "http://kumquat.emse.fr/utilitaires"
    at "jjutils.xq" ;
    
declare namespace xcl = "urn:schemas-microsoft-com:office:spreadsheet";

declare function local:get-timestamp($datecell as node()) as xs:integer
{
let $date := xs:dateTime(string($datecell))
return jj:date-to-millis($date)
};

<display>{
let $t := $arguments[1]
let $idxarray := for $string in fn:tokenize($arguments[2],",") return xs:integer($string)
let $cols := fn:tokenize($arguments[3],",")
let $cutoff := xs:integer($arguments[4])
let $analysiscols := $cols[position()>=$cutoff]
let $d := doc($t)/xcl:Workbook/xcl:Worksheet[position()=$idxarray]
let $times := for $row at $p in $d/xcl:Table/xcl:Row
		return local:get-timestamp($row/xcl:Cell[1])
for $row at $p in $d/xcl:Table/xcl:Row
    let $time := $times[$p]
    let $index := fn:count($times[position()<$p][. = $time])
    let $total := fn:count($times[. = $time])
		let $millis := $time (:+ 24*60*60*1000*($index+1) idiv ($total+1):)
		order by $time
		return
		 (<item>{
    		<info name="time"><time><date>{$millis}</date><duration>2</duration></time></info>,
    		<info name="src-anchor">{
      		<anchor>{
        		<doc>{ $t }</doc>,
        		<path>{jj:build-Path($row)}</path>
      	  }</anchor>
    		}</info>,
    		(for $col at $colp in $cols[position()<$cutoff] 
    		let $s := string($row/xcl:Cell[$colp])
    		let $nonnullstring := if ($s) then $s else "_"
    		return <info name="{$col}">{$nonnullstring}</info>),
    		<info name="coding">_</info>
    		}</item>,
		 for $analcol at $deltap in $analysiscols
		 let $analval := string($row/xcl:Cell[$deltap+$cutoff])
		 	return
		 	if ($analval) then 
  		<item>{
    		<info name="time"><time><date>{$millis}</date><duration>2</duration></time></info>,
    		<info name="src-anchor">{
      		<anchor>{
        		<doc>{ $t }</doc>,
        		<path>{jj:build-Path($row)}</path>
      	  }</anchor>
    		}</info>,
    		(for $col at $colp in $cols[position()<$cutoff] 
    		let $s := string($row/xcl:Cell[$colp])
    		let $nonnullstring := if ($s) then $s else "_"
    		return <info name="{$col}">{$nonnullstring}</info>),
    		<info name="coding">{$analval}</info>
  		}</item>
  		else 
  		())
}</display>
